
/*
 * @项目名称: 模板开发
 * @FilePath: /meek/src/utils/Animation.js
 * @Author: kongxueyang@datatang.com
 * @Date: 2021-05-06T16:58:52+08:00
 * @LastEditors: kongxueyang@datatang.com
 * @LastEditTime: 2021-05-06T16:58:52+08:00
 * Copyright (c) 2018-2022 
 */
                                                    
const requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame;

export default class Animation {
  constructor(fps = 60, callback) {
    this.fps = fps;
    this.callback = callback;
    this.requestID = null;
    this._isPause = false;
  }

  start() {
    if (!this._isPause && this.requestID) {
      return ;
    }
    this._isPause = false;
    const interval = 1000 / this.fps;
    if (requestAnimationFrame) {
      let then = performance.now();
      const tolerance = 0.1;
      const animateLoop = (now) => {
        if (this._isPause) {
          return ;
        }
        this.requestID = requestAnimationFrame(animateLoop);
        const delta = now - then;
  
        if (delta >= interval - tolerance) {
          then = now - (delta % interval);
          this.callback(this);
        }
      };
      this.requestID = requestAnimationFrame(animateLoop);
    } else {
      const animateLoop = () => {
        if (this._isPause) {
          return ;
        }
        this.callback(this);
        setTimeout(() => {
          this.callback(this);
        }, interval)
      }
      setTimeout(animateLoop, interval);
    }
  }

  pause() {
    if (this._isPause) {
      return ;
    }
    this._isPause = true;
    if (this.requestID !== null) {
      cancelAnimationFrame(this.requestID);
      this.requestID = null;
    }
  }
} 
